import dao.StudentMapper;
import entity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class main {

    public static void main(String[] args) throws Exception {
        //通过Mybatis包中的Resources对象很轻松的获取到配置文件
        String resouce="resource/mybatis-cfg.xml";
        Reader reader = Resources.getResourceAsReader(resouce);
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = factory.openSession();
        StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
        // insertStudent(sqlSession, studentMapper);  //新增
        //updateStudent(sqlSession, studentMapper);   //更新
        //selectById(sqlSession, studentMapper);  //查询一条

        selectAll(sqlSession, studentMapper);  //查询所有的

    }


    //新增Student测试
    private static void insertStudent(SqlSession sqlSession, StudentMapper studentMapper) throws Exception {
        Student student=new Student();
        student.setId(4);
        student.setName("小明");
        student.setAge(12);
        student.setSex("男");
        student.setTeacher_id(5);
        studentMapper.insertStudent(student);
        sqlSession.commit();
        sqlSession.close();
    }


    //更新Student
    private static void updateStudent(SqlSession sqlSession, StudentMapper studentMapper) throws Exception {
        Student student=new Student();
        student.setId(4);
        student.setName("小明");
        student.setAge(77);
        student.setTeacher_id(777);
        studentMapper.updateStudent(student);
        sqlSession.commit();
        sqlSession.close();
    }
    //根据id查询一个
    private static void  selectById(SqlSession sqlSession, StudentMapper studentMapper) throws Exception {
        Student student=studentMapper.selectOneById(3);
        System.out.println("id:"+student.getId()+",name:"+student.getName()+",sex"+student.getSex()+",age"+student.getAge());


        sqlSession.close();
    }

    //查询所有的
    private   static void  selectAll(SqlSession sqlSession, StudentMapper studentMapper){
        List<Student> students = studentMapper.selectAllStudent();
        for (Student student:students){
            System.out.println("id:"+student.getId()+",name:"+student.getName()+",sex"+student.getSex()+",age"+student.getAge());
        }
        sqlSession.close();
    }
}
